/*//////////////////////////
///////20120204/////////
/////Shim sang woo/////
////////G-sensor/////////
*///////////////////////////

package com.example.ddakji;

import java.io.IOException;

import android.os.Bundle;
import android.os.Vibrator;
import android.app.Activity;
import android.content.Context;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.Camera;
import android.hardware.Sensor; 
import android.hardware.SensorEvent; 
import android.hardware.SensorEventListener; 
import android.hardware.SensorManager; 
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class MainActivity extends Activity implements SensorEventListener { 

	Vibrator vibrator;	//진동사용
	
    private long lastTime; 
    private float speed; 
    private float lastX; 
    private float lastY; 
    private float lastZ; 
    private float x, y, z; 

    private static final int SHAKE_THRESHOLD = 800; 
    @SuppressWarnings("deprecation")
	private static final int DATA_X = SensorManager.DATA_X; 
    @SuppressWarnings("deprecation")
	private static final int DATA_Y = SensorManager.DATA_Y; 
    @SuppressWarnings("deprecation")
	private static final int DATA_Z = SensorManager.DATA_Z; 

    private SensorManager sensorManager; 
    private Sensor accelerormeterSensor;
 
    boolean cap = false;
    
    public static String IMAGE_FILE = "capture.jpg";
    
    CameraSurfaceView cameraView;
    
    TextView text1, text2, text3;
    
 
    
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);		//위에 제목줄 삭제
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //화면 꺼짐 방지
		
        setContentView(R.layout.activity_main);

        //cameraView = new CameraSurfaceView(getApplicationContext());
        //RelativeLayout previewFrame = (RelativeLayout) findViewById(R.id.relative1);
        //previewFrame.addView(cameraView);		//카메라 보임
        
        vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);	//진동사용
        
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
        accelerormeterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        
        text1 = (TextView)findViewById(R.id.textView1);
        text2 = (TextView)findViewById(R.id.textView2);
        text3 = (TextView)findViewById(R.id.textView3);
        
    } 
    

   
    @Override 
    public void onStart() { 
        super.onStart(); 
        if (accelerormeterSensor != null) 
            sensorManager.registerListener(this, accelerormeterSensor, 
                    SensorManager.SENSOR_DELAY_GAME); 
    } 

    @Override 
    public void onStop() { 
        super.onStop(); 
        if (sensorManager != null) 
            sensorManager.unregisterListener(this); 
    } 

    @Override 
    public void onAccuracyChanged(Sensor sensor, int accuracy) { 
    } 

    
    @SuppressWarnings("deprecation")
	@Override 
    public void onSensorChanged(SensorEvent event) { 

        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { 
            long currentTime = System.currentTimeMillis(); 
            long gabOfTime = (currentTime - lastTime); 

            x = event.values[SensorManager.DATA_X]; 
            y = event.values[SensorManager.DATA_Y]; 
            z = event.values[SensorManager.DATA_Z]; 
            speed = Math.abs(x + y + z - lastX - lastY - lastZ) / gabOfTime * 10000;
            
            //text1.setText(""+x);
            //text2.setText(""+y);
            text3.setText(""+z);
            
            if (gabOfTime > 90&&z>7) {
                lastTime = currentTime; 
                if (speed > SHAKE_THRESHOLD&& speed > 2300) { 
                	cap = true;
                	Toast.makeText(getApplicationContext(),""+speed,Toast.LENGTH_SHORT).show();	
                	//현재 가장 빠를때 메소드 실행 => 멈춘 후 실행으로 교체
                }
                else if(speed<1300&&cap){
                	cap=false;	
                	try {
						Thread.sleep(30);
						vibrator.vibrate((long)speed/3);//잠깐 울린다.
						
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                	/*
                	cameraView.capture(new Camera.PictureCallback() {
                        public void onPictureTaken(byte[] data, Camera camera) {
                        	
                            try {
                                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                                String outUriStr = MediaStore.Images.Media.insertImage(getContentResolver(),bitmap, "Captured Image", "Captured Image using Camera.");
                                
                                if (outUriStr == null) {
                                    Log.d("SampleCapture", "Image insert failed.");
                                    return;
                                } else {
                                    Uri outUri = Uri.parse(outUriStr);
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, outUri));
                                }
                                Toast.makeText(getApplicationContext(), "사진촬영 완료", Toast.LENGTH_LONG).show();
                                camera.startPreview();
                            } catch (Exception e) {
                                Log.e("SampleCapture", "Failed to insert image.", e);
                            }
                        	camera.startPreview();
                        }
                    });*/
                }
                lastX = event.values[DATA_X]; 
                lastY = event.values[DATA_Y]; 
                lastZ = event.values[DATA_Z]; 
            } 
        } 
    }  
    
    public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
    	
    	private SurfaceHolder mHolder;
    	private Camera camera = null;
    	
    	@SuppressWarnings("deprecation")
    	public CameraSurfaceView(Context context) {
    		super(context);
    		// TODO Auto-generated constructor stub
    		
    		mHolder = getHolder();
    		mHolder.addCallback(this);
    		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    	}

    	@Override
    	public void surfaceCreated(SurfaceHolder holder) {
    		// TODO Auto-generated method stub
    		camera = Camera.open();
    		
    		try {
    			camera.setPreviewDisplay(mHolder);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}

    	@Override
    	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    		// TODO Auto-generated method stub
    		camera.startPreview();
    	}
    	
    	@Override
    	public void surfaceDestroyed(SurfaceHolder holder) {
    		// TODO Auto-generated method stub
    		camera.stopPreview();
    		camera = null;
    	}
    	
    	public boolean capture(Camera.PictureCallback handler){
    		if(camera !=null){
    			camera.takePicture(null, null, handler);
    			return true;
    		}else{
    			return false;
    		}
    	}
    }

}
